package com.mysoft.gfyx.marketdevelop.service.impl;

import com.mysoft.framework.modeling.dto.*;
import com.mysoft.framework.service.AppService;
import com.mysoft.gfyx.common.dto.ListResult;
import com.mysoft.gfyx.marketdevelop.controller.dto.GetDetailDataRequestDto;
import com.mysoft.gfyx.marketdevelop.mip.GetDeveloperDataService;
import com.mysoft.gfyx.marketdevelop.mip.dto.TjCustom.MohurdProjectListRequestDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.TjCustom.SqlApiResponseDto;
import com.mysoft.gfyx.marketdevelop.service.DeveloperService;
import com.mysoft.gfyx.marketdevelop.service.LoadDataApiCommonService;
import com.mysoft.gfyx.marketdevelop.service.MohurdProjectService;
import com.mysoft.gfyx.marketdevelop.service.ProjectService;
import org.json.JSONArray;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class MohurdProjectServiceImp extends BaseDataApiServiceImp implements MohurdProjectService {
    @Autowired
    private DeveloperService developerService;

    @Autowired
    private GetDeveloperDataService getDeveloperDataService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private LoadDataApiCommonService loadDataApiCommonService;

    public FieldsSetting loadFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("uuid");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "mohurd_project";
        fieldsSetting.getFields().add(new DataApiField("id", groupName, "主键id", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("prj_num", groupName, "项目编码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("prj_name", groupName, "项目名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("build_corp_name", groupName, "建设单位", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizing_code", groupName, "建设单位信用代码", FieldType.String));

        fieldsSetting.getFields().add(new DataApiField("all_invest", groupName, "总投资(万)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("prj_size", groupName, "建筑规模", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("all_area", groupName, "总面积(平方米)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("conscorp_name", groupName, "施工单位", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("address", groupName, "项目地址", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("prj_approval_date", groupName, "立项日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("tender_result_date", groupName, "中标日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("contract_date", groupName, "合同签订日期", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("release_date", groupName, "开工许可证发证日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("licence_check_depart_name", groupName, "发证机关", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("builder_licence_num", groupName, "施工许可证编号", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("begin_date", groupName, "计划开工日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("end_date", groupName, "计划竣工日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("b_date", groupName, "实际开工日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("e_date", groupName, "实际竣工日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province", groupName, "区域（省）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_code", groupName, "区域（省）Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city", groupName, "区域（市）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city_code", groupName, "区域（市）Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("county", groupName, "县（区）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("is_price_gt_avg", groupName, "高端项目标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("prj_type_num", groupName, "工程用途", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("prj_property_num", groupName, "建筑性质", FieldType.String));

        fieldsSetting.getFields().add(new DataApiField("time_type", groupName, "时间类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("time_begin", groupName, "开始时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("time_end", groupName, "结束时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company_type_label", groupName, "企业类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company_type_label_string", groupName, "建设单位企业类型(拼接)", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("top_developer_name", groupName, "顶级公司", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("top_organizing_code", groupName, "顶级公司信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("top_company_type_label", groupName, "顶级公司企业类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("top_company_type_label_string", groupName, "顶级公司企业类型(拼接)", FieldType.String));

        // 返回
        return fieldsSetting;
    }

    public ListDataResult loadData(LoadDataParams options) {
        MohurdProjectListRequestDto dto = new MohurdProjectListRequestDto();
        dto.setPageNum(options.getPageIndex() + 1);
        dto.setPageSize(options.getPageSize());
        dto.setProvince_code(options.getOptions().getContext().get("province_code").toString());
        if (options.getOptions().getContext().get("city_code") != null) {
            dto.setCity_code(options.getOptions().getContext().get("city_code").toString());
        }
        dto.setTime_begin(options.getOptions().getContext().get("time_begin").toString());
        dto.setTime_end(options.getOptions().getContext().get("time_end").toString());
        dto.addFilterByLoadDataApi(options.getOptions().getFilters());
        if (dto.getTime_type() == null) {
            dto.setIs_all_time("1");
        }

        if (dto.getProvince_code() != null && dto.getProvince_code().equals("0")) {
            dto.setProvince_code("");//如果是0,表示全国，则设置为空
        }
        SqlApiResponseDto res = getDeveloperDataService.mohurdProjectList(dto);
        if (res.getData() == null || res.getData().getRows().size() == 0) {
            ListDataResult result = new ListDataResult();
            result.setTotal(0);
            result.setData(new ArrayList<>());
            return result;
        }

        ListResult<Map<String, Object>> listDataResult = new ListResult<>();
        listDataResult.setTotal(res.getData().getTotalNum());
        res.getData().getRows().forEach(p -> {
            this.processMohurdProject(p, 1);
        });
        listDataResult.setData(res.getData().getRows());
        //处理返回数据结构
        ListDataResult result = new ListDataResult();
        result.setTotal(listDataResult.getTotal());
        result.setData(listDataResult.getData());
        return result;
    }

    /**
     * @param p
     * @param type type=1是默认，type=2是卡片组件
     * @return
     */
    public Map<String, Object> processMohurdProject(Map<String, Object> p, Integer type) {
        if (p.get("build_corp_name") != null) {
            String[] developerNameArr = p.get("build_corp_name").toString().split(",");
            if (developerNameArr.length > 1) {
                p.put("isMultiDeveloper", 1);
            } else {
                p.put("isMultiDeveloper", 0);
            }
        } else {
            p.put("isMultiDeveloper", 0);
        }

        if (p.get("company_type_label") != null) {
            p.put("company_type_label_string", p.get("company_type_label").toString());
            String[] companyTypeLabelArr = p.get("company_type_label").toString().split(",");
            p.put("company_type_label", companyTypeLabelArr);
        } else {
            p.put("company_type_label_string", "");
        }

        if (p.get("top_company_type_label") != null) {
            p.put("top_company_type_label_string", p.get("top_company_type_label").toString());
            String[] topCompanyTypeLabelArr = p.get("top_company_type_label").toString().split(",");
            p.put("top_company_type_label", topCompanyTypeLabelArr);
        } else {
            p.put("top_company_type_label_string", "");
        }

        if (p.get("organizing_code") != null) {
            String[] organizingCodeArr = p.get("organizing_code").toString().split(",");
            if (type.equals(1)) {
                p.put("organizing_code", organizingCodeArr);
            } else {
                try {
                    JSONArray jsonArray = new JSONArray(organizingCodeArr);
                    p.put("organizing_code", jsonArray.toString());
                } catch (JSONException e) {

                }
            }
            if (organizingCodeArr.length > 0) {
                p.put("organizing_code_string", organizingCodeArr[0]);
            }
        }

        if (p.get("top_organizing_code") != null) {
            String[] topOrganizingCodeArr = p.get("top_organizing_code").toString().split(",");
            p.put("top_organizing_code", topOrganizingCodeArr);
        }

        if (p.get("begin_date") != null && p.get("begin_date").toString().length() >= 10)
            p.put("begin_date", p.get("begin_date").toString().substring(0, 10));
        if (p.get("end_date") != null && p.get("end_date").toString().length() >= 10)
            p.put("end_date", p.get("end_date").toString().substring(0, 10));
        if (p.get("contract_date") != null && p.get("contract_date").toString().length() >= 10)
            p.put("contract_date", p.get("contract_date").toString().substring(0, 10));
        if (p.get("prj_approval_date") != null && p.get("prj_approval_date").toString().length() >= 10)
            p.put("prj_approval_date", p.get("prj_approval_date").toString().substring(0, 10));
        if (p.get("release_date") != null && p.get("release_date").toString().length() >= 10)
            p.put("release_date", p.get("release_date").toString().substring(0, 10));
        if (p.get("tender_result_date") != null && p.get("tender_result_date").toString().length() >= 10)
            p.put("tender_result_date", p.get("tender_result_date").toString().substring(0, 10));
        if (p.get("b_date") != null && p.get("b_date").toString().length() >= 10)
            p.put("b_date", p.get("b_date").toString().substring(0, 10));
        if (p.get("e_date") != null && p.get("e_date").toString().length() >= 10)
            p.put("e_date", p.get("e_date").toString().substring(0, 10));

        if (p.get("province") != null && p.get("city") != null) {
            String provinceName = p.get("province").equals(p.get("city")) ? "" : p.get("province").toString();
            String cityName = p.get("city") == null ? "" : p.get("city").toString();
            String countyName = p.get("county") == null ? "" : p.get("county").toString();
            p.put("province_and_city", provinceName + cityName + countyName);
        }

        return p;
    }

    public void FilterProvince(List<Filter> filters) {
        if (filters.size() > 0) {
            for (int i = 0; i < filters.size(); i++) {
                if (filters.get(i).getCondition().size() > 0 && filters.get(i).getCondition().get(0).getField().equals("province_code") && filters.get(i).getCondition().get(0).getValue().equals("0")) {
                    filters.remove(i);
                }
            }
        }
    }

    public Map<String, Object> getProjectDetail(GetDetailDataRequestDto dto) {
        //项目详情
        return projectService.getProjectMainData(dto.getId());
    }

}
